package fi.foyt.cs.persistence.dao.system;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.system.ExternalLinkVerificationCode;

public class ExternalLinkVerificationCodeDAO extends GenericDAO<ExternalLinkVerificationCode> {
  
  public ExternalLinkVerificationCode create(Long userId, String verificationCode, String extra) {
    EntityManager entityManager = getEntityManager();
    
    entityManager.getTransaction().begin();
    try {
      ExternalLinkVerificationCode externalLinkVerificationCode = new ExternalLinkVerificationCode();
      externalLinkVerificationCode.setUserId(userId);
      externalLinkVerificationCode.setVerificationCode(verificationCode);
      externalLinkVerificationCode.setExtra(extra);
      entityManager.persist(externalLinkVerificationCode);
      entityManager.getTransaction().commit();
      
      return externalLinkVerificationCode;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }
  
  public ExternalLinkVerificationCode findByVerificationCode(String verificationCode) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select p from ExternalLinkVerificationCode p where verificationCode = :verificationCode");
    query.setParameter("verificationCode", verificationCode);
    return getSingleResult(query);
  }
}